package com.letv.android.client.utils;

import android.content.Context;
import android.media.AudioManager;
import android.os.Build;
import com.ledim.app.LeDimApplication;
import com.letv.core.utils.LetvUtils;

/**
 * Created by PanJiafang on 15/12/18.
 */
public class AudioManagerUtils implements AudioManager.OnAudioFocusChangeListener{

    AudioManager mAudioManager;
    private Context mContext;

    // other fields here, you'll probably hold a reference to an interface
    // that you can use to communicate the focus changes to your Service

    public AudioManagerUtils() {
        mContext = LeDimApplication.getInstance();
        mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        if (mAudioManager != null) {
            if (mAudioManager.getMode() == AudioManager.MODE_INVALID) {
                mAudioManager.setMode(AudioManager.MODE_NORMAL);
            }
        }
    }

    /**
     * 获取AudioManager
     * @return
     */
    public AudioManager getAudioManager() {
        return mAudioManager;
    }

    /**
     * 请求Focus,暂停其他应用音频输出
     */
    public void requestFocus() {
        if (mAudioManager != null) {
            if (LetvUtils.getSDKVersion() >= Build.VERSION_CODES.KITKAT)
                mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE);
            else
                mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
        }
    }

    /**
     * 移除Focus,开启其他应用音频输出
     */
    public void abandonFocus() {
        if (mAudioManager != null)
            mAudioManager.abandonAudioFocus(this);
    }

    @Override
    public void onAudioFocusChange(int focusChange) {
        // let your service know about the focus change
    }
}
